package com.zxt.te.client;

import com.alibaba.fastjson.JSON;
import com.zxt.te.dto.SendEmailApiDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

/**
 * @author zxt
 */
@Component
@Slf4j
public class MailClient {


    private final JavaMailSender jsm;


    @Value("${spring.mail.username:}")
    private String username;

    @Autowired
    public MailClient(JavaMailSender jsm) {
        this.jsm = jsm;
    }

    public Boolean sendEmail(SendEmailApiDTO dto) {
        try {
            log.info("邮件发送,入参:{}", JSON.toJSONString(dto));
            //建立邮箱消息
            SimpleMailMessage message = new SimpleMailMessage();
            //发送者
            message.setFrom(username);
            //接收者
            message.setTo(dto.getToEmail());
            //发送标题
            message.setSubject(dto.getSubject());
            //发送内容
            message.setText(dto.getContent());
            jsm.send(message);
            return Boolean.TRUE;
        } catch (Exception e) {
            log.error("邮件发送异常", e);
        }
        return Boolean.FALSE;
    }
}
